/*
 * File:    UART.c
 * Project:	HobbyPilotFirmware (HPF)
 * Author:  Wouter van Verre
 *
 * Created on February 8, 2011, 10:33 PM
 */

/** Includes **/
#include "Header.h"

void initUART1(void)
{
    // Set up the U1MODE register
    U1MODEbits.UARTEN = 0;      // Disable the UART1 module while making changes
    U1MODEbits.USIDL  = 1;      // Discontinue operation while in IDLE mode
    U1MODEbits.ALTIO  = 1;      // Use the alternate IO pins
    U1MODEbits.WAKE   = 0;      // Don't wake up the mcu when detecting a START bit
    U1MODEbits.LPBACK = 0;      // Don't enable loopback mode
    U1MODEbits.ABAUD  = 0;      // Don't enable auto baud detection mode
    U1MODEbits.PDSEL  = 0;      // 8-bit data, no parity
    U1MODEbits.STSEL  = 0;      // Use one STOP bit

    // Set up the U1STA bits
    U1STAbits.UTXISEL = 1;      // Generate an interrupt when the transmit buffer becomes empty
    U1STAbits.UTXBRK  = 0;      // Operate U1TX normally
    U1STAbits.UTXEN   = 0;      // Disable UART1 transmission
    U1STAbits.URXISEL = 0;      // Generate an interrupt on every character received
    U1STAbits.ADDEN   = 0;      // Disable address detection mode

    // Set up the U1BRG register
    U1BRG = 7;                  // 125,000 @ Fcy = 10MHz

    // Enable the UART1 module
    U1MODEbits.UARTEN = 1;       // Enable the UART1 module
    U1STAbits.UTXEN   = 1;       // Enable UART1 transmission
}

void __attribute__((__interrupt__, __no_auto_psv__)) _U1TXInterrupt (void)
{
	EnterInterrupt();

	writeToUART1();
    
	IFS0bits.U1TXIF = 0;	// Clear the UART1 module transmission interrupt flag
}

void __attribute__((__interrupt__, __no_auto_psv__)) _U1RXInterrupt (void)
{	
	EnterInterrupt();

	uint8 RxChar;
	while (U1STAbits.URXDA)
	{
		RxChar = U1RXREG;	
		writeByteToCircularBuffer(&UART1RXBuffer, RxChar);
		readFromUART1();
	}

    IFS0bits.U1RXIF = 0;	// Clear the UART1 module recieve interrupt flag
}

void writeToUART1(void)
{
	if ((UART1TXBuffer.numOfPlacesTaken > 0) && (U1STAbits.UTXBF == 0))
	{
		uint8 TxChar;
		readByteFromCircularBuffer(&UART1TXBuffer, &TxChar);
		U1TXREG = (uint16) TxChar;
		writeToUART1();
	}
}

void readFromUART1(void)
{

}
